# -*- coding: utf-8 -*-
import re
import requests
import subprocess


# ##########################################
# 主程序开始
# ##########################################
# 定义查询的日期
# 定义更新的报关单数量
# 使用cookie
# 登录信息
pic_url = 'http://www.npedi.com/edi/ediweb/image.jsp'
pic_url = 'http://www.npedi.com/edi/ediweb/jcaptcha.jpg'
login_url = 'http://www.npedi.com/edi/webLoginAction.do'
auth_url = 'http://127.0.0.1:50003/auth_npedi'
# index_url='http://www.npedi.com/edi/ediweb/index.jsp'
post_data = dict()
post_data['usercode'] = 'GUEST'
post_data['password'] = 'guest'
post_data['randcode'] = ''
post_data['x'] = '0'
post_data['y'] = '0'
login_pattern = '<font color="#FF3300" >GUEST</font>'

# 登录的地址

def randcode(pic):
    with open('code.jpg', 'wb') as f1:
        f1.write(pic)
    subprocess.call('tesseract.exe code.jpg code digits')
    with open('code.txt') as f2:
        t = f2.read()
    print 'txt:', t
    t = re.findall('\d', t)
    if len(t) == 4:
        return ''.join(t)
    else:
        return ''

def getpic(url):

    r = requests.get(url)
    code = randcode(r.content)
    return code, r.cookies


def checkpic(url, code):
    while not re.match('\d{4}', code):
        print 'pic check fail'
        code, cookies = getpic(url)
        # code='1'
    print 'pic check ok'
    return code, cookies


def gethtml(url, params, cookies):
    # post_data['randcode']=''
    login_html = requests.get(url, params=params, cookies=cookies).text
    return login_html


def checkhtml(url, params, cookies, html):
    while not re.search(login_pattern, html):
        print 'login fail'
        html = gethtml(url, params, cookies)
        # html=''
    print 'success'
    return True


def savecookie(url, cookie):
    data = {'cookie': cookie, 'site': 'npedi', 'action': 'remote'}
    headers = {'Accept': 'application/json'}
    r = requests.post(url, data=data, headers=headers)
    print r.text


def refresh(url):
    params = {'site': 'npedi', 'action': 'remote'}
    headers = {'Accept': 'application/json'}
    auth = requests.get(auth_url, params=params, headers=headers).json()
    return requests.get(url, cookies=dict(JSESSIONID=auth['cookie'])).text if auth['result'] else ''

html = refresh(login_url)
if re.search(login_pattern, html):
    print 'session alive'
else:
    print 'session expired'
    post_data['randcode'], cookies = checkpic(pic_url, post_data['randcode'])
    print post_data['randcode'], cookies

    if checkhtml(login_url, post_data, cookies, html):
        savecookie(auth_url, cookies['JSESSIONID'])
